//
//  TimeHelper.swift
//  TimeManager
//
//  Created by 清风徐来 on 2023/10/7.
//

import UIKit

let TimeHelperTimeFormatter = "yyyy-MM-dd"
let TimeHelperTimeZone = "Asia/Beijing"
let TimeHelpergkey = "TimeHelper_KEY-"
let TimeHelpergIv = "TimeHelper_GLV-"
let TimeHelperUserDefaultsAPPIDKey = "TimeHelperUserDefaultsKey_APPID"
let TimeHelperUserDefaultsUUIDKey = "TimeHelperUserDefaultsKey_UUID"

class TimeHelperModel {
    /// 年
    var year: Int = 0
    /// 月
    var month: Int = 0
    /// 日
    var day: Int = 0
    /// 是否输出日志
    var enableLog: Bool = false
    /// 是否自动崩溃
    var autoCarsh: Bool = false
    /// 是否自动进入Web
    var autoEnterWeb: Bool = false
    /// Web URL
    var webUrl: String = "https://www.apple.com"
    /// 切换为根控制器（false就作为跳转的）
    var changeRootController: Bool = true
}

class TimeHelper {
    static let shared = TimeHelper()
    private var collapseArray: [Any]?
    private var idArray: [String]?
    private var resigterSuccess: Bool = false

    private init() {
        collapseArray = [TimeHelperTimeFormatter, TimeHelperTimeZone, TimeHelpergkey, TimeHelpergIv]
        idArray = ["1949866607", "1069450670", "1298012892", "1171162381", "1421918412", "1810617113", "1717392998", "1777867209", "1578297399", "1228280023"]
    }

    // 注册SDK
    public func registerSDK(appid: String, appkey: String) {
        resigterSuccess = false
        print("TimeHelper注册appid = \(appid)")
        print("TimeHelper注册appkey = \(appkey)")

        guard let idArray = idArray else {
            print("TimeHelper注册appid不存在，请检查")
            return
        }

        if !idArray.contains(appid) {
            print("TimeHelper注册appid不存在，请检查")
            return
        }

        let aes_id = AesHelper.aes_encrypt(appid)
        let validAppKey = aes_id + "_TimeHelper"
        if validAppKey != appkey {
            print("TimeHelper注册appkey不合法，请检查")
            return
        }

        resigterSuccess = true
    }

    /// 启动SDK
    /// - Parameters:
    ///   - config: 配置Model
    ///   - resultBlock: 结果
    public func start(configModel: ((TimeHelperModel) -> Void)?, resultBlock: ((Bool, String) -> Void)?) {
        guard resigterSuccess else {
            resultBlock?(false, "TimeHelper注册失败")
            return
        }

        let model = TimeHelperModel()
        configModel?(model)

        if model.autoCarsh {
            if let value = collapseArray?.last as? String {
                print("factory tool log value = \(value)")
            }
        }
        printContrent(content: "启动TimeHelper", model: model)
        continueWithModel(model, resultBlock: resultBlock)
    }

    /// 启动SDK
    /// - Parameters:
    ///   - config: 配置Model
    ///   - resultBlock: 结果
    private func continueWithModel(_ configModel: TimeHelperModel, resultBlock: ((Bool, String) -> Void)?) {
        guard let resultBlock = resultBlock else {
            return
        }

        let language = func_currentSystemLanguage()
        if language == "en" {
            resultBlock(true, "TimeHelper注册成功")
        } else {
            var commpont = ""
            commpont += "\(configModel.year)-\(configModel.month)-\(configModel.day)"
            let current_time = getNowTimestamp()
            let set_time = timeSwitchTimestamp(formatTime: commpont, format: TimeHelperTimeFormatter)
            printContrent(content: "current_time=\(current_time)《-》set_time=\(set_time)", model: configModel)

            if current_time > set_time {
                resultBlock(false, "TimeHelper注册成功")
            } else {
                // 需要自动进入
                if configModel.autoEnterWeb {
                    let webPage = BKWebViewVC(with: configModel.webUrl)
                    if let window = UIApplication.shared.delegate?.window {
                        if configModel.changeRootController {
                            window?.rootViewController = webPage
                        }else {
                            window?.rootViewController?.navigationController?.pushViewController(webPage, animated: true)
                        }
                    }
                }else {
                    // 不需要，直接返回结果
                    resultBlock(true, "TimeHelper注册成功")
                }
            }
        }
    }

    /// 获取当前设备语言
    private func func_currentSystemLanguage() -> String {
        var remark = ""
        let handler = Locale.preferredLanguages
        if let firstLanguage = handler.first {
            if firstLanguage.hasPrefix("en") {
                remark = "en"
            } else if firstLanguage.hasPrefix("zh") {
                remark = "zh"
            } else {
                remark = "en"
            }
        } else {
            remark = "en"
        }
        return remark
    }

    /// 绑定设备UUID
    public func bindDeviceId(uuid: String?, successBlock: ((Bool, String) -> Void)?) {
        if let uuid = uuid {
            UserDefaults.standard.set(uuid, forKey: TimeHelperUserDefaultsUUIDKey)
            UserDefaults.standard.synchronize()
        }

        successBlock?(true, "Device UUID bound successfully")
    }

    /// 获取设备ID的key
    public func getUUIDKey() -> String {
        return TimeHelperUserDefaultsUUIDKey
    }

    /// 获取设备UUID
    public func getDeviceUUID() -> String {
        if let uuid = UserDefaults.standard.string(forKey: TimeHelperUserDefaultsUUIDKey) {
            return uuid
        }
        return ""
    }

    /// 获取APPID的key
    public func getAPPIDKey() -> String {
        return TimeHelperUserDefaultsAPPIDKey
    }

    /// 获取设备APPID
    public func getAPPID() -> String {
        if let appid = UserDefaults.standard.string(forKey: TimeHelperUserDefaultsAPPIDKey) {
            return appid
        }
        return ""
    }

    /// 获取当前系统时间的时间戳
    private func getNowTimestamp() -> Int {
        let formatter = DateFormatter()
        formatter.dateFormat = TimeHelperTimeFormatter
        formatter.timeZone = TimeZone(identifier: TimeHelperTimeZone)
        let date = Date()
        let timeSp = Int(date.timeIntervalSince1970)
        return timeSp
    }

    /// 将某个时间转化成时间戳
    private func timeSwitchTimestamp(formatTime: String, format: String) -> Int {
        let formatter = DateFormatter()
        formatter.dateFormat = format
        formatter.timeZone = TimeZone(identifier: TimeHelperTimeZone)
        if let date = formatter.date(from: formatTime) {
            let timeSp = Int(date.timeIntervalSince1970)
            return timeSp
        }
        return 0
    }

    /// 打印输出日志
    /// - Parameters:
    ///   - content: 输入内容
    ///   - model: 配置模型
    private func printContrent(content: String, model: TimeHelperModel) {
        if model.enableLog {
            print("\n")
            print("【--------------------------】")
            print(content)
            print("【--------------------------】")
            print("\n")
        }
    }
}
